﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace CrazyTalk.Common
{
    /// <summary>
    /// 加密长度枚举
    /// </summary>
    /// <remarks></remarks>
    public enum ELenType
    {
        /// <summary>
        /// 8位MD5加密
        /// </summary>
        Len8,
        /// <summary>
        /// 16位MD5加密
        /// </summary>
        Len16
    }
    /// <summary>
    /// MD5加密类
    /// </summary>
    /// <remarks></remarks>
    public class MD5
    {

        /// <summary>
        /// 默认使用utf-8编码
        /// 产生32长度MD5加密
        /// </summary>
        /// <param name="Input">The input.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string MD5Encrypt(string Input)
        {
            byte[] b = Encoding.UTF8.GetBytes(Input);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');

            return ret;
        }
        /// <summary>
        ///  产生枚举长度MD5加密
        /// </summary>
        /// <param name="Input">The input.</param>
        /// <param name="Half">if set to <c>true</c> [half].</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string MD5Encrypt(string Input, ELenType type)
        {
            //编译以后首次运行MD5Encrypt(Input); 比 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Input, "MD5").ToLower();快8倍左右
            string output = MD5Encrypt(Input); //System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Input, "MD5").ToLower();
            switch (type)
            {
                case ELenType.Len8:
                     output = output.Substring(8, 8);//16位MD5加密（取32位加密的9~25字符）
                    break;
                case ELenType.Len16:
                    output = output.Substring(8, 16);//16位MD5加密（取32位加密的9~25字符）
                    break;
                default:
                    break;
            }           
            return output;
        }
    }
}
